package org.example.casLoginDemo.controller;


import org.example.casLoginDemo.contast.Result;
import org.example.casLoginDemo.po.User;
import org.example.casLoginDemo.service.LoginService;
import org.example.casLoginDemo.util.JWTUtils;
import org.example.casLoginDemo.util.LoginValidate;
import org.example.casLoginDemo.util.PassToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class LoginController {
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private LoginService loginService;

    @PassToken
    @RequestMapping("/chickLogin")
    public Result checkLogin (@RequestBody User user, HttpServletRequest request){
        Result res = new Result();
        logger.info("chickLogin入参{}",user.toString());
        //获取用户信息
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("uname",user.getUname());
        map.put("pwd",user.getPwd());
        List<User> usersList = loginService.getUser(map);
        if(usersList.size() == 1){
            User userInfo = usersList.get(0);
            //获取token
            Map<String,String> tokenMap = new HashMap<>();
            tokenMap.put("uname",userInfo.getUid());
            tokenMap.put("pwd",userInfo.getUname());
            String token = JWTUtils.getToken(tokenMap);
            return res.ok(token);
        }else{
            return res.fail("密码或账号错误！！");
        }
    }

    @RequestMapping("/register")
    public Result register (@RequestBody User user){
        Result res = new Result();
        logger.info("register{}",user.toString());
        int num = loginService.addUser(user);
        if(num==1){
            return res.ok();
        }else{
            return res.fail("注册账户失败！");
        }
    }

    @LoginValidate("herong.com")
    @RequestMapping("/gettest")
    public void gettest (HttpServletResponse response) throws IOException {
        Result res = new Result();
        logger.info("执行方法11111111111111");
        res.setReturn(response,0,"您好");
    }


    @LoginValidate("herong.com")
    @RequestMapping("/loginout")
    public void loginOut(){
        System.out.println("***** 登出系统 ***********");

    }

    @PreDestroy
    public void delete(){
        System.out.println("*****Bean销毁前***********");
    }

}
